package com.ssyc.student.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.OneKeyShareCallback;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.ShareManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.bean.ErrorQuestionsInfo;
import com.ssyc.student.bean.ShareLessonInfo;
import com.ssyc.student.bean.StudyStateInfo;
import com.ssyc.student.bean.UnitBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import okhttp3.Call;

/**
 * 学生端---题型选择界面
 * Created by Administrator on 2018/5/9 0009.
 */


@Route(path = "/student/StudentChooseQuestionTypeActivity")
public class StudentChooseQuestionTypeActivity extends BaseActivity implements View.OnClickListener {

    //加载布局
    private RelativeLayout rlLoadingView;

    //内容布局
    private LinearLayout llContent;

    private ImageView ivBack;
    private ImageView ivErrorQuestion;
    private ImageView ivPlaycardRed;
    private ImageView ivChyx;
    private ImageView ivChjcNew;
    private ImageView ivKeyx;
    private ImageView ivYxjc;
    private ImageView ivChjc;
    private ImageView ivYfjc;
    private ImageView ivPlaycardYellow;
    private ImageView ivXz;
    private ImageView ivYd;

    @Autowired(name = "gradeId")
    String gradeId;

    @Autowired(name = "lessonId")
    String lessonId;

    @Autowired(name = "classId")
    String classId;

    public static final String LESSONDATA = "StudentChooseQuestionTypeActivity.this";

    //通知页面刷新的标识
    public static final int UPDATAPAGESTATE = 0x220;

    //当前Lesson对象
    private UnitBean.DataBean.GradeListBean info;

    private String num;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_choose_question_new_type;
    }

    @Override
    protected void init() {

        LogUtils.iTag("test", "走了这个类方法了88888888888888888");

        //初始化视图
        initView();

        showContent();

        //取出Intent的值
        getLessonData();

        //请求服务器数据
        http();
    }


    /**
     * 获取当前页面的Lesson对象
     */
    private void getLessonData() {
        info = (UnitBean.DataBean.GradeListBean) getIntent().getSerializableExtra(LESSONDATA);

        num = getIntent().getStringExtra("num");
        if (info == null) {
            //教师端跳入
            ARouter.getInstance().inject(this);
            info = new UnitBean.DataBean.GradeListBean();
            info.setGrade_id(gradeId);
            info.setLesson_id(lessonId);
        }
    }

    /**
     * 初始化View的方法
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        ivErrorQuestion = findViewById(R.id.iv_error_question);
        ivErrorQuestion.setOnClickListener(this);
        ivPlaycardRed = findViewById(R.id.iv_playcard_red);
        ivPlaycardRed.setOnClickListener(this);
        ivChyx = findViewById(R.id.iv_chyx);
        ivChyx.setOnClickListener(this);
        ivKeyx = findViewById(R.id.iv_kwyx);
        ivKeyx.setOnClickListener(this);
        ivYxjc = findViewById(R.id.iv_yxjc);
        ivYxjc.setOnClickListener(this);
        ivChjc = findViewById(R.id.iv_chjc);
        ivChjc.setOnClickListener(this);
        ivYfjc = findViewById(R.id.iv_yfjc);
        ivYfjc.setOnClickListener(this);
        ivChjcNew = findViewById(R.id.iv_kwyx_new);
        ivChjcNew.setOnClickListener(this);
        ivPlaycardYellow = findViewById(R.id.iv_playcard_yellow);
        ivPlaycardYellow.setOnClickListener(this);
        ivXz = findViewById(R.id.iv_xz);
        ivXz.setOnClickListener(this);
        ivYd = findViewById(R.id.iv_yd);
        ivYd.setOnClickListener(this);
        rlLoadingView = findViewById(R.id.rl_loading);
        llContent = findViewById(R.id.ll_content);
        rlLoadingView.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);


        int width = ScreenUtils.getScreenWidth(this);

        int ivSize = 0;

        //计算图片的大小,动态计算图片显示大小

        if (ScreenUtils.isPad(this)) {
            ivSize = width / 10;
        } else {
            ivSize = width * 74 / 370;
        }

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ivSize, ivSize);

        //统一设置所有图片的大小,根据屏幕的比列来计算
        List<ImageView> imageViews = new ArrayList<>();

        imageViews.add(ivChyx);
        imageViews.add(ivKeyx);
        imageViews.add(ivYxjc);
        imageViews.add(ivChjc);
        imageViews.add(ivYfjc);
        imageViews.add(ivXz);
        imageViews.add(ivYd);
        imageViews.add(ivKeyx);
        imageViews.add(ivChjcNew);
        for (int i = 0; i < imageViews.size(); i++) {
            imageViews.get(i).setLayoutParams(lp);
        }
    }


    /**
     * 请求服务器数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "27");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lesson", info.getLesson_id());
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.STUDYSTATE, map, this, rlLoadingView, llContent, new HttpUtils.SucceedCallBack() {
            @Override
            public void onSucceed(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    StudyStateInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, StudyStateInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            List<String> data = info.getData();
                            if (data != null && data.size() != 0) {
                                setPageState(data);
                            } else {
                                //data是空保持默认状态
                                setPageStateInit();
                            }
                        } else {
                            UiUtils.Toast("返回异常码是:" + info.getState(), false);
                        }
                    } else {
                        Log.i("test", "数据器返回数据为空");
                    }
                }
            }
        });
    }


    /**
     * 当所有模块都没做,服务器返回的是空,这里只打开词汇预习可点击状态
     */
    private void setPageStateInit() {

        //新加词汇检测
        ivChjcNew.setImageResource(R.drawable.st_khjc_new_normal);
        ivChjcNew.setEnabled(false);

        //课文预习
        ivKeyx.setImageResource(R.drawable.st_kwyx_no);
        ivKeyx.setEnabled(false);

        //预习检测
        ivYxjc.setImageResource(R.drawable.st_yxjc_no);
        ivYxjc.setEnabled(false);

        //词汇检测
        ivChjc.setImageResource(R.drawable.st_chjc_no);
        ivChjc.setEnabled(false);

        //语法检测
        ivYfjc.setImageResource(R.drawable.st_yfjc_no);
        ivYfjc.setEnabled(false);

        //写作
        ivXz.setImageResource(R.drawable.st_xz_no);
        ivXz.setEnabled(false);

        //阅读
        ivYd.setImageResource(R.drawable.st_yd_no);
        ivYd.setEnabled(false);

        //隐藏2个打开按钮
        ivPlaycardRed.setVisibility(View.INVISIBLE);
        ivPlaycardYellow.setVisibility(View.INVISIBLE);
    }


    /**
     * 设置页面状态的方法
     * 词汇预习10 课文预习11 预习检测12 词汇检测13 语法检测14 写作15 阅读16
     * 规则:
     *
     * @param data
     */
    private void setPageState(List<String> data) {
        if (data.contains("10")) {
            //表示新加词汇检测可以学习,可以点击
            ivChjcNew.setImageResource(R.drawable.st_kwyx);
            ivChjcNew.setEnabled(true);
        } else {
            ivChjcNew.setImageResource(R.drawable.st_kwyx_no);
            ivChjcNew.setEnabled(false);
        }

        if (data.contains("18")) {
            //表示课文预习可以学习,可以点击
            ivKeyx.setImageResource(R.drawable.st_kwyx);
            ivKeyx.setEnabled(true);
        } else {
            ivKeyx.setImageResource(R.drawable.st_kwyx_no);
            ivKeyx.setEnabled(false);
        }

        if (data.contains("11")) {
            //表示预习检测可以学习,可以点击
            ivYxjc.setImageResource(R.drawable.st_yxjc);
            ivYxjc.setEnabled(true);
        } else {
            ivYxjc.setImageResource(R.drawable.st_yxjc_no);
            ivYxjc.setEnabled(false);
        }

        if (data.contains("12")) {
            //表示词汇检测可以学习,可以点击
            ivChjc.setImageResource(R.drawable.st_chjc);
            ivChjc.setEnabled(true);
            ivXz.setImageResource(R.drawable.st_xz);
            ivXz.setEnabled(true);
            //表示阅读可以学习,可以点击
            ivYd.setImageResource(R.drawable.st_yd);
            ivYd.setEnabled(true);

        } else {
            ivChjc.setImageResource(R.drawable.st_chjc_no);
            ivChjc.setEnabled(false);

            ivXz.setImageResource(R.drawable.st_xz_no);
            ivXz.setEnabled(false);
            ivYd.setImageResource(R.drawable.st_yd_no);
            ivYd.setEnabled(false);
        }

        if (data.contains("13")) {
            //表示语法检测可以学习,可以点击
            ivYfjc.setImageResource(R.drawable.st_yfjc);
            ivYfjc.setEnabled(true);
        } else {
            ivYfjc.setImageResource(R.drawable.st_yfjc_no);
            ivYfjc.setEnabled(false);
        }

//        if (data.contains("14")) {
//            //表示写作可以学习,可以点击
//            ivXz.setImageResource(R.drawable.st_xz);
//            ivXz.setEnabled(true);
//            //表示阅读可以学习,可以点击
//            ivYd.setImageResource(R.drawable.st_yd);
//            ivYd.setEnabled(true);
//        } else {
//            ivXz.setImageResource(R.drawable.st_xz_no);
//            ivXz.setEnabled(false);
//            ivYd.setImageResource(R.drawable.st_yd_no);
//            ivYd.setEnabled(false);
//        }

        //确定打卡按钮的显示与隐藏
        if (data.contains("12")) {
            //显示红色打卡
            ivPlaycardRed.setVisibility(View.VISIBLE);
        } else {
            ivPlaycardRed.setVisibility(View.INVISIBLE);
        }

        if (data.contains("14")) {
            //显示黄色打卡
            ivPlaycardYellow.setVisibility(View.VISIBLE);
        } else {
            ivPlaycardYellow.setVisibility(View.INVISIBLE);
        }

    }


    /**
     * 当用户答完题提交后需要重新刷新该页面 的状态
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.getType() == UPDATAPAGESTATE) {
            http();
        }
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_error_question) {
            //错题集

            if ("0".equals(AccountUtils.getRole(this))) {
                Intent intent = new Intent(StudentChooseQuestionTypeActivity.this, StudentErrorQuestionsActivity.class);
                intent.putExtra(StudentVocabularyPreviewActivity.LESSONID, info.getLesson_id());
                startActivity(intent);
            } else if ("2".equals(AccountUtils.getRole(this))) {
                Intent intent = new Intent(StudentChooseQuestionTypeActivity.this,
                        ErrorQuestionsListActivity.class);
                intent.putExtra(StudentVocabularyPreviewActivity.LESSONID, info.getLesson_id());
                intent.putExtra("num", num);
                startActivity(intent);
            }


        } else if (id == R.id.iv_playcard_yellow) {
            //黄色复习打卡,分享的操作
            punchCard(1);
        } else if (id == R.id.iv_playcard_red) {
            //红色预习打卡按钮,分享
            punchCard(0);
        } else if (id == R.id.iv_chyx) {
            //词汇预习
            Intent intent = new Intent(this, StudentVocabularyPreviewActivity.class);
            intent.putExtra(StudentVocabularyPreviewActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentVocabularyPreviewActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_kwyx_new) {
            //新添加的词汇检测界面
            Intent intent = new Intent(this, StudentAddVocabularyDetectionActivity.class);
            intent.putExtra(StudentVocabularyPreviewActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentVocabularyPreviewActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_kwyx) {
            //课文预习
            Intent intent = new Intent(this, StudentTextPrepareActivity.class);
            intent.putExtra(StudentTextPrepareActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentTextPrepareActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_yxjc) {
            //预习检测
            Intent intent = new Intent(this, StudentPrepareDetectionActivity.class);
            intent.putExtra(StudentPrepareDetectionActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentPrepareDetectionActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_chjc) {
            //词汇检测
            Intent intent = new Intent(this, StudentVocabularyDetectionActivity.class);
            intent.putExtra(StudentVocabularyDetectionActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentVocabularyDetectionActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_yfjc) {
            //语法检测
            Intent intent = new Intent(this, StudentGrammarDetectionActivity.class);
            intent.putExtra(StudentPrepareDetectionActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentPrepareDetectionActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_xz) {
            //写作
            Intent intent = new Intent(this, StudentWriteActivity.class);
            intent.putExtra(StudentPrepareDetectionActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentPrepareDetectionActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        } else if (id == R.id.iv_yd) {
            //阅读
            Intent intent = new Intent(this, StudentReadActivity.class);
            intent.putExtra(StudentReadActivity.LESSONID, info.getLesson_id());
            intent.putExtra(StudentReadActivity.GRADEID, info.getGrade_id());
            startActivity(intent);
        }
    }

    /**
     * 请求服务器判断是否有错题
     */
    private void isemptyList(String lessonId) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "31");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lessonId", lessonId);
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
//        map.put("acc", "15608630008");
//        map.put("lessonId", "1");
//        map.put("role","0");
//        map.put("apptoken", "WHBHWJDSAKDAKSDNSAJDAK");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.ERRORQUESTIONS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                ErrorQuestionsInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ErrorQuestionsInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        if (info.getData().getError_list() != null && info.getData().getError_list().size() != 0) {

                        } else {
                            UIHelper.showToast(StudentChooseQuestionTypeActivity.this,
                                    "目前没有产生错题");
                        }
                    } else {
                        Log.i("test", info.getState() + "");
                    }
                }
            }
        });
    }

    /**
     * 打卡记录
     */
    private void punchCard(int type) {

        //请求服务器
        Map<String, String> map = new HashMap<>();
        map.put("type", "34");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("lessonId", info.getLesson_id());
        map.put("module", type + "");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.SHARELESSON, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                PopUpManager.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {

                PopUpManager.dismiss();

                if (!TextUtils.isEmpty(response)) {
                    ShareLessonInfo shareInfo = null;
                    try {
                        shareInfo = GsonUtil.jsonToBean(response, ShareLessonInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    Log.i("test", "单元：" + response);
                    if (null != shareInfo) {
                        if ("200".equals(shareInfo.getState())) {
                            //返回成功
                            ShareLessonInfo.DataBean data = shareInfo.getData();
                            if (null != data) {
                                //分享掌握单词,学习时长,累计掌握单词,累计学习时长
                                doShareAction(type, info.getLesson_id(), data.getStu_word(), data.getStu_text(), data.getStu_time());
                            }
                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("返回异常码是:" + shareInfo.getState(), false);
                            Log.i("test", "返回异常码是:" + shareInfo.getState());
                        }
                    }
                }
            }
        });
    }

    /**
     * 分享的方法
     */
    private void doShareAction(int type, String pos, String count, String learn,
                               String times) {
        //分享地址
        String shareUrl = HttpAdress.UPDATE_URL + "JPXB/sharePage/pages/JPXB/new_2_sharing_interface/share_revise_preparation.html?" +
                "acc=" + AccountUtils.getAccount(this) +
                "&role=" + AccountUtils.getRole(this) +
                "&lessonId=" + pos + "&module=" + type;
        //分享地址
//        String imgUrl = "http://139.129.57.83:8080/Appandroid/jpxblogo.png";
        String imgUrl = "https://www.ycsjedu.com/share/Appandroid/jpxblogo.png";


        //分享标题
        String title = AccountUtils.getName(this) + "同学在金牌学霸" + "lesson" + pos +
                getType(type) + "了" + count + "个单词，" + learn + "篇课文,该课学习了" + times + "分钟";

        ShareManager.newInstance().showOneShare(this, title, shareUrl, "分享内容", imgUrl, shareUrl, new OneKeyShareCallback() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.i("test", "分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("test", "分享失败");
                Log.i("test", "报错码是" + i);
                LogUtils.iTag("test", GsonUtil.objectToJson(throwable));
            }

            @Override
            public void onCancel(Platform platform, int i) {

                Log.i("test", "取消分享");
            }
        });
    }

    /**
     * 判断预习复习
     */
    private String getType(int type) {
        String TYPE = "学习";
        if (type == 0) {
            //预习
            TYPE = "预习";
        } else if (type == 1) {
            TYPE = "复习";
        }
        return TYPE;
    }
}
